package com.hongsuan.pplive.mobileAPI.auth;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;

import com.hongsuan.pplive.common.utils.HttpsUtil;
import com.hongsuan.pplive.mobileAPI.utils.JsonUtils;

public class QQLoginAPI {

	public static String appId = "xxx";
	public static String appSecret = "xxx";
	public static String baseUrl = "https://graph.qq.com";
	protected static final String URL_GET_USERINFO = baseUrl
			+ "/user/get_user_info?access_token=%s&oauth_consumer_key=%s&openid=%s";
	protected static final long ACCESS_TIMEOUT = 15;
	protected static final String DEF_APP_TOKEN_EXPIRE = "3h";

	/**
	 * 获取用户信息
	 * 
	 * <pre>
	 * http://wiki.connect.qq.com/get_user_info
	 * 
	 * 
	 * 调用地址：
	 * https://graph.qq.com/user/get_user_info
	 * 参数
	 *   access_token=*************&
	 *   oauth_consumer_key=12345&
	 *   openid
	 * 
	 * 返回结果如下：
	 * {
	 *     "ret": 0,
	 *     "msg": "",
	 *     "is_lost": 0,
	 *     "nickname": "小吞",
	 *     "gender": "女",
	 *     "province": "广东",
	 *     "city": "广州",
	 *     "year": "1993",
	 *     "figureurl": "http://qzapp.qlogo.cn/qzapp/101207268/982C9FEADAF7B242C5069B8F390784BF/30",
	 *     "figureurl_1": "http://qzapp.qlogo.cn/qzapp/101207268/982C9FEADAF7B242C5069B8F390784BF/50",
	 *     "figureurl_2": "http://qzapp.qlogo.cn/qzapp/101207268/982C9FEADAF7B242C5069B8F390784BF/100",
	 *     "figureurl_qq_1": "http://q.qlogo.cn/qqapp/101207268/982C9FEADAF7B242C5069B8F390784BF/40",
	 *     "figureurl_qq_2": "http://q.qlogo.cn/qqapp/101207268/982C9FEADAF7B242C5069B8F390784BF/100",
	 *     "is_yellow_vip": "0",
	 *     "vip": "0",
	 *     "yellow_vip_level": "0",
	 *     "level": "0",
	 *     "is_yellow_year_vip": "0"
	 * }
	 * </pre>
	 * 
	 * @param accessToken
	 * @return
	 * @throws IOException
	 */
	public static QQUserInfo getUserInfo(String accessToken, String openid) throws IOException {
		if (StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(openid)) {
			return null;
		}
		String url = String.format(URL_GET_USERINFO, accessToken, appId, openid);
		String resultString = HttpsUtil.getter(url, "", "UTF-9");
		
		// DefaultHttp.get(url,
																	// ACCESS_TIMEOUT,
																	// "UTF-8");

		// Logger.debug("[sso-qq]get userinfo. use url '%s'", url);
		QQUserInfo userinfo = JsonUtils.fromJson(resultString, QQUserInfo.class);
		if (userinfo == null || !userinfo.hasGot()) {
			// Logger.debug("[sso-qq]get userinfo failed, with result of '%s'",
			// resultString);
			return null;
		}

		// Logger.debug("[sso-qq]get userinfo success, with result of '%s'",
		// resultString);
		return userinfo;
	}
}
